package com.kehao.leetcode.algorithm;
//https://leetcode-cn.com/problems/add-two-numbers/
public class Solution2 {
    class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }


    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode head = new ListNode();head.next = null;
        ListNode rear = head;
        int jinwei = 0;
        while (l1!=null&&l2!=null){
            ListNode p = new ListNode();
            int val = l1.val+l2.val+jinwei;
            if(val>= 10){
                jinwei = val/10;
                val = val%10;
            }else {
                jinwei = 0;
            }
            p.val = val;
            rear.next = p;
            rear = p;
            l1 = l1.next;
            l2 = l2.next;
        }
        while (l1!=null){
            ListNode p = new ListNode();
            int val = l1.val+jinwei;
            if(val>= 10){
                jinwei = val/10;
                val = val%10;
            }else {
                jinwei = 0;
            }
            p.val = val;
            rear.next = p;
            rear = p;
            l1 = l1.next;
        }
        while (l2!=null){
            ListNode p = new ListNode();
            int val = l2.val+jinwei;
            if(val>= 10){
                jinwei = val/10;
                val = val%10;
            }else {
                jinwei=0;
            }
            p.val = val;
            rear.next = p;
            rear = p;
            l2 = l2.next;
        }
        if(jinwei!=0){
            ListNode p = new ListNode();
            p.val = jinwei;
            rear.next = p;
        }
        return head.next;
    }
}
